from datetime import datetime
import requests
import math
import pandas as pd

# 读取数据
jj_rc = pd.read_excel(r'../Fund_form_files/JJ_all.xlsx',
                      dtype={'基金代码': str, '基金名称': str, '板块': str})
list_jz = []
list_time = []
gz = []
gzf = []


def get_fund_data(fund_code, page_count=1):
    for page in range(1, page_count + 1):
        url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex={page}&pageSize=20"
        headers = {'Referer': 'http://fundf10.eastmoney.com', 'User-Agent': 'Mozilla/5.0'}
        try:
            r = requests.get(url, headers=headers, timeout=10)
            data = r.json()['Data']['LSJZList']
            for item in data:
                list_jz.append(float(item['DWJZ']))
                list_time.append(item['FSRQ'])
        except Exception as e:
            print(f"基金 {fund_code} 历史数据获取失败: {e}")
    try:
        gz_url = f"http://fundgz.1234567.com.cn/js/{fund_code}.js"
        gz_response = requests.get(gz_url, timeout=10)
        gz_data = gz_response.text
        gz.append(float(gz_data.split('gsz":"')[1].split('","')[0]))
        gzf.append(float(gz_data.split('gszzl":"')[1].split('","')[0]))  # 估算涨幅
    except Exception as e:
        print(f"基金 {fund_code} 当日估值获取失败: {e}")


if __name__ == '__main__':
    jj_code = jj_rc['基金代码'].values
    jj_name = jj_rc['基金名称'].values
    jj_type = jj_rc['板块'].values
    now_time = datetime.now().strftime('%m月%d日')
    with open(f'分析log/{now_time}入场分析报告', 'w', encoding='utf-8') as f:
        for i in range(len(jj_code)):
            get_fund_data(jj_code[i])
            pass_ma5 = sum(list_jz[:5]) / 5
            pass_ma20 = sum(list_jz[:20]) / 20
            now_ma5 = (sum(list_jz[:4]) + gz[0]) / 5
            now_ma20 = (sum(list_jz[:19]) + gz[0]) / 20
            my_bz_c = math.sqrt(
                sum((x - pass_ma20) ** 2 for x in list_jz[:20]))  # 计算20日标准差(波动率)
            upper_band = pass_ma20 + 2 * my_bz_c  # 布林带上轨 = 中轨 + 2倍标准差
            lower_band = pass_ma20 - 2 * my_bz_c  # 布林带下轨 = 中轨 - 2倍标准差
            print(f'正在分析{jj_name[i]}({jj_code[i]})')
            if pass_ma5 <= pass_ma20 and now_ma5 > now_ma20 and gz[0] < upper_band:
                f.write(f'🔍{jj_name[i]}({jj_code[i]})\n')
                f.write(f'🍞板块：{jj_type}\n')
                f.write(f'💹当日估值: {gz[0]:.2f} | 估算涨幅: {gzf[0]:.2f}%\n')
                f.write("💰金叉\n")
            gz.clear()
            list_jz.clear()
            list_time.clear()
